import {messages} from "share/common";
/**
 * 操作：转交
 * 适用：差旅，费用申请单
 */
import React from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import { Form, Button, Modal, Select, message, Row, Col, Alert } from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
import debounce from 'lodash.debounce'
import requestService from 'containers/request/request.service'

class TransferBtn extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      formType: null,
      info: {},
      showTransferBtn: false, //是否显示【转交】按钮
      transferVisible: false,
      userList: [],
      userOID: '', //转交人oid
      userName: '', //转交人name
      applicationList: menuRoute.getRouteItem(this.props.url,'key'), //申请单列表页
    }
    this.handleSearch = debounce(this.handleSearch, 500);
  }

  componentWillMount(){}

  componentWillReceiveProps(nextProps) {
    if (!this.state.formType || !this.state.info.applicationOID) {
      this.setState({
        formType: nextProps.formType,
        info: nextProps.info
      }, () => {
        this.checkShowTransferBtn();
      });
    }
  }

  //校验是否展示转交按钮
  checkShowTransferBtn = () => {
    //差旅或费用单，开启了转交配置，状态为已通过，当前登录人为申请人或者统一报销人，且整单未停用
    if ((this.state.formType === 2001 || this.state.formType === 2002)
      && (this.props.loginUser.userOID === this.state.info.applicantOID || this.props.loginUser.userOID === this.state.info.uniformReimbursementClerkOID)
      && this.state.info.status === 1003
      && this.props.transferEnable === 'true'
      && !this.state.info.closed
    ) {
      this.setState({showTransferBtn: true});
    } else {
      this.setState({showTransferBtn: false});
    }
  };

  getUserList = (keyword) => {
    //人员靠搜索
    let params = {
      page: 0,
      size: 10,
      status: 1001, //在职
      roleType: 'TENANT', //账套级别，跨公司的
      setOfBooksId: this.props.loginCompany.setOfBooksId
    };
    if (keyword) {
      params.keyword = keyword;
    }
    requestService.getUser(params).then(res => {
      if (res.data) {
        this.setState({
          userList: res.data.length ? res.data : []
        });
      }
    }).catch(err =>{
      if (err.response && err.response.data) {
        message.error(err.response.data.message);
      }
    });
  };

  handleChange = (value) => {
    //handleChange的执行顺序在handleSelect之后，userName的值会被覆盖掉
    let existName = null;
    this.state.userList.map(user => {
      if (user.userOID === value) {
        existName = user.fullName;
      }
    });
    this.setState({
      userName: existName ? existName : value
    });
  };

  handleSelect = (e, opt) => {
    this.setState({
      userOID: opt.props['data-user'].userOID,
      userName: opt.props['data-user'].fullName
    });
  };

  handleSearch = (keyword) => {
    this.setState({
      userOID: ''
    }, () => {
      this.getUserList(keyword);
    });
  };

  onBlur = () => {
    if (!this.state.userOID) {
      this.setState({
        userName: '',
        userList: []
      });
    }
  };

  showTransferModal = () => {
    this.setState({
      transferVisible: true
    });
  };

  closeTransferModal = () => {
    this.setState({
      transferVisible: false,
      userName: '',
      userOID: '',
      userList: []
    });
  };

  handleTransfer = () => {
    if (this.state.info && this.state.info.applicationOID && this.state.userOID) {
      this.setState({loading: true});
      requestService.setTransfer(this.state.info.applicationOID, this.state.userOID).then(res => {
        this.setState({loading: false});
        message.success(messages('request.key528')/*转交成功*/);
        this.context.router.push(this.state.applicationList.url);
      }).catch(err =>{
        if (err.response && err.response.data) {
          message.error(err.response.data.message);
        }
        this.setState({loading: false});
      });
    }
  };

  render() {
    const { transferVisible, userList, userOID, userName, loading, showTransferBtn } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 13, offset: 1 },
    };
    return (
      <div className="request-btn">
        {showTransferBtn && (
          <Button onClick={this.showTransferModal}>{messages('request.key529')/*转交*/}</Button>
        )}
        <Modal title={messages('request.key529')/*转交*/} visible={transferVisible} onCancel={this.closeTransferModal} maskClosable={false} destroyOnClose={true}
               footer={[
                 <Button key="back" onClick={this.closeTransferModal}>{messages('common.cancel')/*取消*/}</Button>,
                 <Button key="submit" type="primary" loading={loading} disabled={!userOID} onClick={this.handleTransfer}>{messages('common.ok')/*确定*/}</Button>
               ]}
        >
          <Form>
            <Row>
              <Col span={24}>
                <Alert
                  style={{marginBottom: 24}}
                  message={messages('request.key530')/*转交后，所选转交人员可关联该申请单进行报销！*/}
                  type="info"
                  showIcon/>
              </Col>
            </Row>
            <FormItem {...formItemLayout} label={messages('request.key531')/*转交给*/}>
              <Select
                mode="combobox"
                placeholder={messages('request.key646')/*请按照姓名/工号/手机号/职位搜索*/}
                defaultActiveFirstOption={false}
                showArrow={false}
                onChange={this.handleChange}
                onSelect={this.handleSelect}
                value={userName}
                filterOption={false}
                onBlur={this.onBlur}
                getPopupContainer={triggerNode => triggerNode.parentNode}
                optionLabelProp="title"
                onSearch={this.handleSearch}>
                {userList.map(item=>
                  <Option data-user={item} value={item.userOID} key={item.userOID} title={item.fullName}>{`${item.fullName}  ${item.employeeID}`}</Option>
                )}
              </Select>
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
}

TransferBtn.propTypes = {
  formType: React.PropTypes.number.isRequired,
  info: React.PropTypes.object.isRequired,
  transferEnable: React.PropTypes.string
};

TransferBtn.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    loginCompany: state.login.loginCompany,
    loginUser: state.login.loginUser
  }
}

const wrappedTransferBtn = Form.create()(TransferBtn);

export default connect(mapStateToProps)(wrappedTransferBtn)
